"""
    Token生成解密

    @author tinaroot.cn
    @time 2022/3/5 15:20
"""
from aiapp.setting import application
from aiapp.utils import des_util, redis_util
import json


def generate_token(content):
    """
    生成token
    :param content:
    :return:
    """
    token = des_util.des_encrypt(application.TOKEN_SECRET_KEY, (content))
    redis_util.redis_client.set(application.TOKEN_CACHE_KEY + token, content, application.TOKEN_CACHE_EXPIRED_KEY)
    return token


def verify_token(token):
    """
    验证TOKEN是否有效
    :param token:
    :return:
    """
    try:
        content = des_util.des_decrypt(application.TOKEN_SECRET_KEY, token)
        cache = redis_util.redis_client.get(application.TOKEN_CACHE_KEY + token)
        if cache == content:
            return True
        else:
            return False
    except Exception:
        return False


def resolve_token(content):
    return des_util.des_decrypt(application.TOKEN_SECRET_KEY, str(content))


if __name__ == "__main__":
    token = generate_token(json.dumps({
        "code": 200,
        "data": False,
        "msg": "请求成功"
    }))
    print(json.loads(resolve_token(token)))
